package com.sunfeng.chap5.selectkey;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class Test301 {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress("localhost", 7777));
        serverSocketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        boolean isRun = true;
        while (isRun == true) {
            int keyCount = selector.select();
            // 获取键集
            Set<SelectionKey> set1 = selector.keys();
            // 获取已选择键集  就绪键集
            Set<SelectionKey> set2 = selector.selectedKeys();

            System.out.println(keyCount);
            System.out.println(set1.size());
            System.out.println(set2.size());
            System.out.println();
            Iterator<SelectionKey> selectionKeyIterator = set2.iterator();

            while (selectionKeyIterator.hasNext()){
                SelectionKey selectionKey = selectionKeyIterator.next();
                ServerSocketChannel serverSocketChannel1 = (ServerSocketChannel)selectionKey.channel();
                // 调用accept方法
                SocketChannel socketChannel = serverSocketChannel1.accept();
                socketChannel.configureBlocking(false);
                SelectionKey selectionKey1 = socketChannel.register(selector, SelectionKey.OP_ACCEPT);
                System.out.println((SelectionKey.OP_READ&~selectionKey1.interestOps())==0);
                System.out.println((SelectionKey.OP_WRITE&~selectionKey1.interestOps())==0);
                SelectionKey selectionKey2 = socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);

                System.out.println(keyCount);
                System.out.println(set1.size());
                System.out.println(set2);
                System.out.println(selectionKey1=selectionKey2);
            }
        }
    }
}
